<template>
<div>
	<Button type="info" size="small" @click="add">添加角色</Button>
	<br><br>
    <Table border :columns="role_table.columns" :data="role_table.data"></Table>
	<Modal ref="modal" title="修改">
		<Form ref="formValidate" :model="role_table.current" :rules="role_table.ruleValidate" :label-width="80">
			<FormItem label="Name" prop="name">
				<Input v-model="role_table.current.name" placeholder="输入角色名称"></Input>
			</FormItem>
		</Form>
		<Checkbox v-model="role_table.current.is_super">设为超级管理员（所有权限）</Checkbox>
		<Collapse value="0" v-if="!role_table.current.is_super">
			<Panel v-for="(group, group_index) in module_items" :name="''+group_index">
				{{ group.name }}
				<div slot="content">
					<Checkbox v-model="group.selected" @click.prevent.native="handleCheckAll(group)">全选</Checkbox>
					<Row v-for="(item,item_index) in group.children">
						<Col span="6">
							<Checkbox v-model="item.selected" @on-change="checkAllGroupChange(group)">{{ item.name }}</Checkbox>
						</Col>
						<Col span="18">
							<Checkbox :disabled="!item.selected" v-for="(operation, operation_index) in item.children" v-model="operation.selected">{{ operation.name }}</Checkbox>
						</Col>
					</Row>
				</div>
			</Panel>
		</Collapse>
		<div slot="footer">
                <Button type="text" size="large" @click="cancel">取消</Button>
                <Button type="primary" size="large" @click="ok('formValidate')">确定</Button>
            </div>
	</Modal>
</div>
</template>

<script>
	import AdminRole from './model/AdminRole'

    export default {
        data () {
            return {
				role_table: {
					columns: [
						{ title: 'ID', key: 'id' },
						{ title: '名称', key: 'name', render: (h, params) => {
							return h('div', [
								h('Icon', {
									props: { type: 'person' }
								}),
								h('strong', params.row.name)
							]);
						}},
						{ title: '操作', key: 'action', width: 150, align: 'center', render: (h, params) => {
							return h('div', [
								h('Button', {
									props: { type: 'primary', size: 'small' },
									style: { marginRight: '5px' },
									on: { click: () => { this.modify(params.index) } }
								}, '修改'),
								h('Button', { 
									props: { type: 'error', size: 'small' },
									on: { click: () => { this.remove(params.index) } }
								}, '删除')
							]);
						}}
					],
					data: [],
					current: {},
					ruleValidate: {
						name: [
							{ required: true, message: '角色名称不能为空', trigger: 'blur' }
						]
					}
				},
                module_items: [
                    { code: "1100", name: "权限管理", selected: false, children: [
						{ code: "1101", name: "角色管理", selected: true, children: [
							{ code: "11", name: "添加", selected: true },
							{ code: "13", name: "修改", selected: false },
							{ code: "12", name: "删除", selected: true }
						] },
						{ code: "1103", name: "管理员管理", selected: true, children: [
							{ code: "11", name: "添加", selected: true },
							{ code: "13", name: "修改", selected: false },
							{ code: "12", name: "删除", selected: true }
						] }
					] },
                    { code: "", name: "系统维护", selected: false, children: [
						{ code: "", name: "数据库", selected: true, children: [
							{ code: "", name: "生成", selected: true },
							{ code: "", name: "备份", selected: false }
						] }
					] }
                ]
            }
        },
        methods: {
			add () {
				var role = new AdminRole();
				role.name = "未命名角色";
				this.role_table.current = role;
				this.role_table.current.mode = "add";
				this.show();
			},
            remove (index) {
				if(confirm("确定要删除角色吗？")) {
					this.api.post("role/admin_delete", { id: this.role_table.data[index].id }, res => {
						this.$Message.success('删除成功!');
						this.role_table.data.splice(index, 1);
					});
				}
            },
			modify(index) {
				this.role_table.current = this.role_table.data[index];
				this.role_table.current.mode = "modify";
				this.show();
			},
			show () {
				this.role_table.current.storageValue();
				setForModuleItems(this.module_items, this.role_table.current.permission); // 遍历设置权限状态
				this.$refs["modal"].visible = true;
			},
            ok (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
						this.role_table.current.permission = getFromModuleItems(this.module_items);
						if(this.role_table.current.mode == "add") {
							this.api.post("role/admin_add", this.role_table.current.serialize(), res => {
								this.role_table.current.id = res.id;
								this.role_table.data.push(this.role_table.current);
								this.$refs["modal"].visible = false;
								this.$Message.success('添加成功!');
							});
						}else {
							this.api.post("role/admin_modify", this.role_table.current.serialize(), res => {
								this.$refs["modal"].visible = false;
								this.$Message.success('修改成功!');
							});
						}
                    } else {
                        this.$Message.error('请正确填写表单!');
						return false;
                    }
                })
            },
            cancel () {
				this.$refs["modal"].visible = false;
				this.role_table.current.applyStorageValue();
                this.$Message.info('已取消');
            },
            handleCheckAll (group) {
				group.selected = !group.selected;
				for(var i = 0, len = group.children.length; i < len; i++) {
					group.children[i].selected = group.selected;
				}
            },
            checkAllGroupChange (group) {
				var all_checked = true;
				for(var i = 0, len = group.children.length; i < len; i++) {
					if(group.children[i].selected == false) {
						all_checked = false;
						break;
					}
				}
				group.selected = all_checked;
            }
        },
		created() {
			this.api.post("search/admin_role", null, res => {
				this.role_table.data = AdminRole.parseList(res.page.list);
			});
		}
    }

	function setForModuleItems(module_items, permission) {
		module_items.forEach(function(group) {
			group.selected = permission[group.code] || false;
			group.children.forEach(function(item) {
				item.selected = permission[item.code] || false;
				item.children.forEach(function(operation) {
					operation.selected = permission[item.code+operation.code] || false;
				});
			});
		});
	}
	function getFromModuleItems(module_items) {
		var permission = {};
		module_items.forEach(function(group) {
			if(group.selected) permission[group.code] = true;
			group.children.forEach(function(item) {
				if(!item.selected) return;
				permission[item.code] = true;
				item.children.forEach(function(operation) {
					if(operation.selected) permission[item.code+operation.code] = true;
				});
			});
		});
		return permission;
	}
</script>